package com.dongdongshop.mq;

import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.service.OrderService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;

@RocketMQTransactionListener
public class RocketMQCallback implements RocketMQLocalTransactionListener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 回调方法
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        TbOrder order = (TbOrder) o;
        System.out.println("订单id:"+order.getOrderId());
        System.out.println("订单号:"+order.getOrderNum());
        System.out.println("交易流水号:"+order.getTardeNo());
        System.out.println("交易状态:"+order.getStatus());

        System.out.println("---------------------------------");
        System.out.println("message 信息"+message.getHeaders());
        System.out.println("message 头部信息"+message.getPayload());
        String messageId = message.getHeaders().getId().toString();
        try {
            System.out.println("调用mapper去修改数据库");
            redisTemplate.opsForValue().set(messageId,"1");
            return RocketMQLocalTransactionState.COMMIT; //消费成功
        } catch (Exception e) {
            e.printStackTrace();
            redisTemplate.opsForValue().set(messageId,"2");
            return RocketMQLocalTransactionState.ROLLBACK; //回滚
        }
    }

    // 回查方法
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String messageId = message.getHeaders().getId().toString();
        String status = redisTemplate.opsForValue().get(messageId);
        if (status != null && status.equals("1")){
            return RocketMQLocalTransactionState.COMMIT;
        }else if (status != null && status.equals("2")){
            return RocketMQLocalTransactionState.ROLLBACK;
        }else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
